package cn.phecda.boot.data.jpa.hibernate;

import cn.phecda.boot.common.lang.exception.BootRuntimeException;
import cn.phecda.boot.common.lang.util.SnowflakeUtils;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.id.IdentifierGenerator;
import org.hibernate.id.factory.spi.CustomIdGeneratorCreationContext;
import org.hibernate.id.factory.spi.StandardGenerator;

import java.lang.reflect.Field;
import java.lang.reflect.Member;
import java.lang.reflect.Method;

/**
 * <p> 雪花ID生成, 支持持String和Long类型  </p>
 *
 * @author : wanpinwei
 */
public class SnowflakeIdentifierGenerator implements IdentifierGenerator, StandardGenerator {
    private final Class<?> propertyType;

    public SnowflakeIdentifierGenerator(SnowflakeIdGenerator generator, Member member, CustomIdGeneratorCreationContext context) {
        // 确定注解字段的类型
        if (member instanceof Method) {
            // 方法上定义
            propertyType = ((Method) member).getReturnType();
        } else {
            // 字段上定义
            propertyType = ((Field) member).getType();
        }
    }

    @Override
    public Object generate(SharedSessionContractImplementor sharedSessionContractImplementor, Object o) {
        if (String.class.isAssignableFrom(propertyType)) {
            return SnowflakeUtils.nextStrId();
        } else if (Long.class.isAssignableFrom(propertyType)){
            return SnowflakeUtils.nextId();
        }

        throw new BootRuntimeException("The snowflake algorithm supports both String and Long types");
    }
}
